import { _decorator, Component, EventTouch, Input, input, instantiate, Node, UITransform, Vec2 } from 'cc'
import DataManager from '../../Global/DataManager'
import { EntityTypeEnum, IActor, InputTypeEnum, toFixed } from '../../Common'
import { EntityManager } from '../../Base/EntityManager'
import { EntityStateEnum, EventEnum } from '../../Enum'
import { WeaponStateMachine } from './WeaponStateMachine'
import EventManager from '../../Global/EventManager'
const { ccclass, property } = _decorator

@ccclass('WeaponManager')
export class WeaponManager extends EntityManager {
    private owner: number // 武器拥有者 id
    private body: Node
    private anchor: Node
    private point: Node

    init(data: IActor) {
        this.owner = data.id
        this.body = this.node.getChildByName('Body')
        this.anchor = this.body.getChildByName('Anchor')
        this.point = this.anchor.getChildByName('Point')

        this.fsm = this.body.addComponent(WeaponStateMachine)
        this.fsm.init(data.weaponType)

        this.state = EntityStateEnum.Idle

        EventManager.Instance.on(EventEnum.BulletBorn, this.handleBulletBorn, this)
        EventManager.Instance.on(EventEnum.WeaponShoot, this.handleWeaponShoot, this)
    }

    onDestory() {
        EventManager.Instance.off(EventEnum.BulletBorn, this.handleBulletBorn, this)
        EventManager.Instance.off(EventEnum.WeaponShoot, this.handleWeaponShoot, this)
    }

    handleBulletBorn(owner: number) {
        if (this.owner !== owner) {
            return
        }

        this.state = EntityStateEnum.Attack
    }

    handleWeaponShoot() {
        if (this.owner !== DataManager.Instance.myPlayerId) {
            return
        }

        const pointWorldPos = this.point.getWorldPosition()
        // 将世界坐标转换为舞台的坐标
        const pointStagePos = DataManager.Instance.stage.getComponent(UITransform).convertToNodeSpaceAR(pointWorldPos)

        const anchorWorldPos = this.anchor.getWorldPosition()
        // 子弹的射击方向
        const direction = new Vec2(pointWorldPos.x - anchorWorldPos.x, pointWorldPos.y - anchorWorldPos.y).normalize()

        // DataManager.Instance.applyInput({
        EventManager.Instance.emit(EventEnum.ClientSync, {
            type: InputTypeEnum.WeaponShoot,
            owner: this.owner,
            position: {
                x: toFixed(pointStagePos.x),
                y: toFixed(pointStagePos.y),
            },
            direction: {
                x: toFixed(direction.x),
                y: toFixed(direction.y),
            },
        })
    }

}